<template>
  <div class="todoapp">
    <!-- 接收它儿子的添加事件 -->
    <TodoHeader
      @addTask="addTask"
      :arr="showList"
    ></TodoHeader>
    <TodoMain
      :arr="showList"
      @delTask="delTask"
    ></TodoMain>
    <TodoFooter
      :length="showList.length"
      @changeShow="changeShow"
      @clearTask="clearTask"
    ></TodoFooter>
  </div>
</template>
 
<script>
import './styles/base.css'
import './styles/index.css'
import TodoHeader from '@/components/TodoHeader'
import TodoMain from '@/components/TodoMain'
import TodoFooter from '@/components/TodoFooter'
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('listData')) || [],
      isShow: 'all' //显示标记，初始为all
    }
  },
  methods: {
    // 添加任务
    addTask(taskName) {
      this.list.push({
        id: this.list.at(-1).id + 1 || 100,
        name: taskName,
        isDone: false
      })
    },
    // 删除任务
    delTask(id) {
      this.list = this.list.filter((obj) => obj.id !== id)
    },
    // 改变显示的标记
    changeShow(flag) {
      this.isShow = flag
    },
    // 清除已完成的任务
    clearTask() {
      this.list = this.list.filter((obj) => obj.isDone === false)
    }
  },
  computed: {
    // 根据设置的标记去切换不同的显示内容
    showList() {
      if (this.isShow === 'yes') {
        return this.list.filter((obj) => obj.isDone === true)
      } else if (this.isShow === 'no') {
        return this.list.filter((obj) => obj.isDone === false)
      } else {
        return this.list
      }
    }
  },
  // 侦听器
  watch: {
    list: {
      deep: true,
      // 数据一旦改变就王本地存一次数据
      handler() {
        localStorage.setItem('listData', JSON.stringify(this.list))
      }
    }
  }
}
</script>

<style scoped>
</style>